//
//  HLOuathViewController.swift
//  HLwWeibo
//
//  Created by hqhxu on 16/2/28.
//  Copyright © 2016年 hqhxu. All rights reserved.
//

import UIKit

import SVProgressHUD

class HLOuathViewController: UIViewController {
    
    override func loadView() {
        self.view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadOuathView()
        
        addNavgationItem()
        
        webView.delegate = self
    }
    
    // MARK -加载ouath授权界面
    func loadOuathView() {
        
        let request = NSURLRequest(URL: HLNeteworkTool.shareInstance.ouathUrl())
        
        webView.loadRequest(request)
    }
    
    //MARK - 添加导航控制器上的item
    func addNavgationItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "setToFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickRightItem")
    }
    
    //MARK - item的点击事件
    
    func setToFill() {
        let js = "document.getElementById('userId').value='546833201@qq.com';document.getElementById('passwd').value='hqhllz1314179'"
        //swift中执行js中的代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func didClickRightItem() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /*
    client_id 	true 	string 	申请应用时分配的AppKey。
    redirect_uri 	true 	string 	授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。
    */
    //MARK -懒加载一个webView
    lazy var webView:UIWebView = UIWebView()

}

extension HLOuathViewController:UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.showWithStatus("正在加载...", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.URL?.absoluteString
        
        //字符串的截取
        if url!.hasPrefix(HLNeteworkTool.shareInstance.redirect_uri) {
            //query 表示？后面的字符串
            let query = request.URL?.query
            
            let codeString = "code="
            
            //判断是否含有code=
            if query!.hasPrefix(codeString) {
                
                //字符串的截取需要使用oc
                let ocQuery = query! as NSString
                
                let code = ocQuery.substringFromIndex(codeString.characters.count)
                
                //发送post请求 保存数据  
                // 保存成功后得通知控制器啊
                HLAccountViewModel.shareInstance.loadAccess_token(code, loadAccessTokenCallBack: { (error) -> () in
                    if error == nil {
                        //成功了
                         UIApplication.sharedApplication().keyWindow?.rootViewController = HLMainController()
                        
                    }else {
                        print("获取accesstoken失败:\(error)")
                    }
                })

            }else { //用户点击了取消按钮 没有授权
                dismissViewControllerAnimated(true, completion: nil)
            }
            
            //发送post请求

            return false
        }
        
        return true
    }
}







